using LCL.Tools;
using LCL.Tools.Build;
using LCL.Tools.WinFrm;
using System;
using System.Collections.Generic;
using System.Data;
using System.Net;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using System.Threading;
using LCL.Threading;
using LCL.Config;
using System.Diagnostics;
using LCL.Caching;

namespace LCL.Tools {
    public partial class MainFrm : BaseFrm {
        DbConfigInfo dbConfig = null;
        public MainFrm() {
            InitializeComponent();
            dbConfig = DbConfig.GetConfig();
        }
        private void MainFrm_Load(object sender, EventArgs e) {
            this.Text = UIFactory.Title + " V" + Application.ProductVersion;
            InitFrm();
        }
        private delegate void DelegetAddNode();
        private void cmbDBlist_SelectedIndexChanged(object sender, EventArgs e) {
            try {
                if (cmbDBlist.SelectedItem == null)
                    return;
                AppConfig.GetInstance().DbName = cmbDBlist.SelectedItem.ToString();
                SetMsg("正在加载...");
                //这里写处理耗时的代码，代码处理完成则自动关闭该窗口
                DelegetAddNode addNode = new DelegetAddNode(this.TreeViewTables);
                this.Invoke(addNode);

            } catch (Exception ex) {
                UIFactory.ShowThreadExceptionDialog(ex);
            }
        }
        private void SetMsg(string msg = "") {
            if (string.IsNullOrWhiteSpace(msg)) {
                msg = "服务器： " + dbConfig.DbHost
                  + " 数据库类型：" + dbConfig.DbType.ToString()
                  + " 数据库：" + cmbDBlist.SelectedItem.ToString()
                  + " 总表数：" + this.treeView1.Nodes.Count;
            }
            this.toolStripStatusLabel1.Text = msg;
        }
        private void TreeViewTables() {
            string keyvalue = this.txt_search.Text;
            this.treeView1.Nodes.Clear();
            #region MyRegion
            var list = Utility.GetDbo().GetTables(AppConfig.GetInstance().DbName);
            if (!string.IsNullOrWhiteSpace(keyvalue)) {
                list = list.FindAll(p => p.TableName.Contains(keyvalue));
            }
            foreach (var item in list) {
                TreeNode node = new TreeNode();
                node.Text = item.TableName + item.TableNameRemark;
                node.Tag = item.TableName;
                node.ImageKey = "table";
                if (string.IsNullOrWhiteSpace(item.TableNameRemark)) {
                    node.ToolTipText = item.TableName;
                } else {
                    node.ToolTipText = item.TableNameRemark;
                }
                this.treeView1.Nodes.Add(node);
            }
            this.treeView1.ExpandAll();
            SetMsg();
            #endregion
        }
        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e) {
            try {
                if (this.treeView1.SelectedNode == null)
                    return;
                TreeNode node = this.treeView1.SelectedNode;
                AppConfig.GetInstance().DbTableName = node.Tag.ToString();
                模板代码生成ToolStripMenuItem_Click(null, null);
            } catch (Exception ex) {
                UIFactory.ShowThreadExceptionDialog(ex);
            }
        }
        private void 生成数据库文档ToolStripMenuItem_Click(object sender, EventArgs e) {
            try {
                FrmDbaDoc frm = new FrmDbaDoc();
                frm.ShowDialog();
            } catch (Exception ex) {
                UIFactory.ShowThreadExceptionDialog(ex);
            }
        }
        private void 修改字段说明ToolStripMenuItem_Click(object sender, EventArgs e) {
            try {
                if (this.treeView1.SelectedNode == null)
                    return;
                TreeNode node = this.treeView1.SelectedNode;
                FrmDbTablesColumnsLable frm = new FrmDbTablesColumnsLable(node.Tag.ToString());
                frm.OnDataSaved += frm_OnDataSaved;
                frm.ShowDialog();
            } catch (Exception ex) {
                UIFactory.ShowThreadExceptionDialog(ex);
            }
        }
        private void frm_OnDataSaved(object sender, EventArgs e) {
            treeView1_AfterSelect(null, null);
        }
        private void 修改表说明ToolStripMenuItem_Click(object sender, EventArgs e) {
            try {
                FrmDbTablesLable frm = new FrmDbTablesLable();
                frm.OnDataSaved += frm_OnDataSaved;
                frm.Show();
            } catch (Exception ex) {
                UIFactory.ShowThreadExceptionDialog(ex);
            }
        }
        private void 添加表主键ToolStripMenuItem_Click(object sender, EventArgs e) {
            if (MessageBox.Show("是否把数据库里所有的ID列添加主键和自增列", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes) {
                添加表主键ToolStripMenuItem.Enabled = false;
                UIFactory.UIDb().AddTableByKey(AppConfig.GetInstance().DbName);
                MessageBox.Show("把数据库里所有的ID列添加主键和自增列成功", "提示");
                添加表主键ToolStripMenuItem.Enabled = true;
            }
        }
        private void 刷新列表ToolStripMenuItem_Click(object sender, EventArgs e) {
            //清空缓存
            LCache.Instance.Clear();
            cmbDBlist_SelectedIndexChanged(null, null);
        }
        private void 相同字段说明一样ToolStripMenuItem_Click(object sender, EventArgs e) {
            try {
                #region 相同字段说明一样
                string filePath = "";
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.Filter = "Excel(*.xls)|*.xls|所有文件(*.*)|*.*";

                ofd.RestoreDirectory = true;
                if (ofd.ShowDialog() == DialogResult.OK) {
                    filePath = ofd.FileName;
                } else {
                    return;
                }
                if (!UIFactory.UIFact().UpdateColumns(filePath)) {
                    MessageBox.Show("xls文件里面必须包含 字段名称，字段说明 这两列，并且文件工作表的名字必须是Sheet1$ ");
                } else {
                    MessageBox.Show("把数据库里相同的字段描述一样修改成功！！！", "提示");
                }
                #endregion
            } catch (Exception ex) {
                UIFactory.ShowThreadExceptionDialog(ex);
            }
        }
        private void labText_Click(object sender, EventArgs e) {
            //访问Blogs
            System.Diagnostics.Process.Start("http://www.cnblogs.com/luomingui");
        }
        private void ShowFormToTabControl(TabControl tc, Form f, string tpText, int imageIndex = 0) {// ShowFormToTabControl(tabControl1, new FrmUpdateHouseHold(), "衡水更新数据");
            foreach (TabPage t in tc.TabPages) {
                if (t.Text == tpText) {
                    tc.SelectedTab = t;
                    f.Dispose();
                    return;
                }
            }
            TabPage tp = new TabPage(tpText);
            tp.ImageIndex = imageIndex;
            f.TopLevel = false;
            f.Parent = tp;
            f.FormBorderStyle = FormBorderStyle.None;
            f.ControlBox = false;
            f.TopMost = false;
            f.Dock = DockStyle.Fill;
            f.Show();
            tc.TabPages.Add(tp);
            tc.SelectedTab = tp;
        }
        private void 设置数据表关系ToolStripMenuItem_Click(object sender, EventArgs e) {
            try {
                if (this.treeView1.SelectedNode == null)
                    return;
                TreeNode node = this.treeView1.SelectedNode;
                ShowFormToTabControl(tabControl1, new FrmDbTableRelation(), "设置数据表关系");
            } catch (Exception ex) {
                UIFactory.ShowThreadExceptionDialog(ex);
            }
        }
        private void 关闭其他全部ToolStripMenuItem_Click(object sender, EventArgs e) {
            foreach (TabPage item in tabControl1.TabPages) {
                if (item.Text != "表说明") {
                    item.Dispose();
                }
            }
        }
        private void 根据类库生成数据库描述ToolStripMenuItem_Click(object sender, EventArgs e) {
            FrmDoc frm = new FrmDoc();
            frm.ShowDialog();
        }
        private void 模板代码生成ToolStripMenuItem_Click(object sender, EventArgs e) {
            try {
                foreach (TabPage item in tabControl1.TabPages) {
                    item.Dispose();
                }
                TreeNode node = this.treeView1.SelectedNode;
                var frm = new FrmTemplateCodeBuilder(node.Tag.ToString());
                frm.InitFrm();
                ShowFormToTabControl(tabControl1, frm, "模板代码生成");
                if (cmbDBlist.SelectedItem == null)
                    return;
                AppConfig.GetInstance().DbName = cmbDBlist.SelectedItem.ToString();
            } catch (Exception ex) {
                UIFactory.ShowThreadExceptionDialog(ex);
            }
        }
        private void 模板代码批量生成ToolStripMenuItem_Click(object sender, EventArgs e) {
            try {
                var frm = new FrmTemplateBatchCodeBuilder();
                frm.ShowDialog();
            } catch (Exception ex) {
                UIFactory.ShowThreadExceptionDialog(ex);
            }
        }
        private void 翻译表字段说明ToolStripMenuItem_Click(object sender, EventArgs e) {
            try {
                if (this.treeView1.SelectedNode == null)
                    return;
                TreeNode node = this.treeView1.SelectedNode;
                UIFactory.UIFact().UpdateColumnRemark(node.Tag.ToString());
                MessageBox.Show(node.Text + "翻译完成,请刷新查看", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            } catch (Exception ex) {
                UIFactory.ShowThreadExceptionDialog(ex);
            }
        }
        private void 模板项目生成ToolStripMenuItem_Click(object sender, EventArgs e) {
            try {
                FrmProjectCodeBuilder frm = new FrmProjectCodeBuilder();
                frm.ShowDialog();
            } catch (Exception ex) {
                UIFactory.ShowThreadExceptionDialog(ex);
            }
        }
        #region 自定义函数
        private void InitFrm() {
            try {
                //数据库列表
                UIFactory.UIFact().BindDataBaseList(this.cmbDBlist);
                if (cmbDBlist.Items.Count > 0) {
                    AppConfig.GetInstance().DbName = cmbDBlist.SelectedItem == null ? "" : cmbDBlist.SelectedItem.ToString();
                    this.toolStripStatusLabel1.Text = "服务器： " + dbConfig.DbHost
                        + " 数据库类型：" + dbConfig.DbType.ToString()
                        + " 数据库：" + AppConfig.GetInstance().DbName
                        + " 总表数：" + this.treeView1.Nodes.Count;
                }
                //默认显示模板生成页面
                foreach (TabPage item in tabControl1.TabPages) {
                    item.Dispose();
                }
                var frm = new FrmTemplateCodeBuilder("");
                frm.InitFrm();
                ShowFormToTabControl(tabControl1, frm, "模板代码生成");

            } catch (Exception ex) {
                UIFactory.ShowThreadExceptionDialog(ex);
            }
        }
        #endregion

        #region 帮助
        private void 关于AToolStripMenuItem_Click(object sender, EventArgs e) {
            try {
                About frm = new About();
                frm.ShowDialog();
            } catch (Exception ex) {
                UIFactory.ShowThreadExceptionDialog(ex);
            }
        }
        private void 源码下载ToolStripMenuItem_Click(object sender, EventArgs e) {
            try {
                Process proc = new Process();
                Process.Start("IExplore.exe", "https://github.com/luomingui");
            } catch {
                MessageBox.Show("请访问：https://github.com/luomingui", "完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        private void 在线帮助ToolStripMenuItem_Click(object sender, EventArgs e) {
            try {
                Process proc = new Process();
                Process.Start("IExplore.exe", "http://www.cnblogs.com/luomingui");
            } catch {
                MessageBox.Show("请访问：http://www.cnblogs.com/luomingui", "完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        #endregion

        private void 项目代码生成ToolStripMenuItem_Click(object sender, EventArgs e) {
            try {
                FrmProjectCodeBuilder frm = new FrmProjectCodeBuilder();
                frm.ShowDialog();
            } catch (Exception ex) {
                UIFactory.ShowThreadExceptionDialog(ex);
            }
        }

        private void 模板代码生成ToolStripMenuItem1_Click(object sender, EventArgs e) {
            try {
                foreach (TabPage item in tabControl1.TabPages) {
                    item.Dispose();
                }
                TreeNode node = this.treeView1.SelectedNode;
                if (node == null)
                    return;
                var frm = new FrmTemplateCodeBuilder(node.Tag.ToString());
                frm.InitFrm();
                ShowFormToTabControl(tabControl1, frm, "模板代码生成");
                if (cmbDBlist.SelectedItem == null)
                    return;
                AppConfig.GetInstance().DbName = cmbDBlist.SelectedItem.ToString();
            } catch (Exception ex) {
                UIFactory.ShowThreadExceptionDialog(ex);
            }
        }

        private void 模板批量生成ToolStripMenuItem_Click(object sender, EventArgs e) {
            try {
                var frm = new FrmTemplateBatchCodeBuilder();
                frm.ShowDialog();
            } catch (Exception ex) {
                UIFactory.ShowThreadExceptionDialog(ex);
            }
        }

        private void 生成数据库文档ToolStripMenuItem1_Click(object sender, EventArgs e) {
            try {
                FrmDbaDoc frm = new FrmDbaDoc();
                frm.ShowDialog();
            } catch (Exception ex) {
                UIFactory.ShowThreadExceptionDialog(ex);
            }
        }

        private void 选项OToolStripMenuItem_Click(object sender, EventArgs e) {
            try {
                OptionFrm frm = new OptionFrm(this);
                frm.ShowDialog();
            } catch (Exception ex) {
                UIFactory.ShowThreadExceptionDialog(ex);
            }
        }

        private void 拼接字符串ToolStripMenuItem_Click(object sender, EventArgs e) {
            try {
                StringTools frm = new StringTools();
                frm.ShowDialog();
            } catch (Exception ex) {
                UIFactory.ShowThreadExceptionDialog(ex);
            }
        }

        private void MainFrm_FormClosing(object sender, FormClosingEventArgs e) {
            //清空缓存
            LCache.Instance.Clear();
        }

        private void txt_search_TextChanged(object sender, EventArgs e) {
            //清空缓存
            LCache.Instance.Clear();
            cmbDBlist_SelectedIndexChanged(null, null);
        }
    }
}
